package com.lifeng.controller;

import com.lifeng.common.util.PageResult;
import com.lifeng.common.util.Result;
import com.lifeng.entity.Student;
import com.lifeng.service.IStudentService;
import com.lifeng.vo.StudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lifeng
 * @since 2025-01-07
 */
@RestController
@RequestMapping("/student")
public class StudentController {

	@Autowired
	private IStudentService studentService;

	// 获取学生列表
	@RequestMapping("/list")
	public Result getStudent() {
		System.out.println("student list");
		return Result.ok().data("list",studentService.list());
	}

	//删除单个,不要了,批量删除也能删单个
//	@DeleteMapping("/delete/{sid}")
//	public Result findByPage(@PathVariable("sid") Integer sid) {
//		studentService.removeById(sid);
//		return Result.ok();
//	}

	// 分页查询（不带条件）
	@GetMapping("/findByPage/{page}/{pageSize}")
	public Result findByPage(@PathVariable("page") Integer page,
	                    @PathVariable("pageSize") Integer pageSize) {
		PageResult<Student> pr = studentService.findByPage(page,pageSize);
		return Result.ok().data("pr",pr);
	}
	// 分页查询（带条件）
	@PostMapping("/search/{page}/{pageSize}")
	public Result search(@PathVariable("page") Integer page,
	                @PathVariable("pageSize") Integer pageSize,
	                @RequestBody(required = false) StudentVO vo){
		PageResult<Student> pr = studentService.search(page,pageSize,vo);
		return Result.ok().data("pr",pr);
	}

	// 添加
	@PostMapping("/add")
	public Result add(@RequestBody Student student){
		boolean flag = studentService.save(student);
		return flag ? Result.ok().message("添加成功!^v^") : Result.error().message("添加失败!>^<");
	}

	//修改
	@PutMapping("/update")
	public Result update(@RequestBody Student student){
		boolean flag = studentService.updateById(student);
		return flag ? Result.ok().message("修改成功!^v^") : Result.error().message("修改失败!>^<");
	}


	// 批量删除
	@DeleteMapping("/delete/{ids}")
	public Result delete(@PathVariable("ids") String ids){
		String[] temp = ids.split(",");
		List<String> list = Arrays.asList(temp);
		return studentService.removeByIds(list) ? Result.ok().message("删除成功!^v^") : Result.error().message("删除失败!>^<");
	}


}
